import { RowDataPacket } from 'mysql2';
import bcrypt from 'bcryptjs';
import pool from '../config/database';

export interface IUser extends RowDataPacket {
  id: number;
  username: string;
  password: string;
  role: 'user' | 'admin';
  created_at: Date;
  updated_at: Date;
}

// 创建用户表
export const createUserTable = async (): Promise<void> => {
  const createTableSQL = `
    CREATE TABLE IF NOT EXISTS users (
      id INT PRIMARY KEY AUTO_INCREMENT,
      username VARCHAR(50) UNIQUE NOT NULL,
      password VARCHAR(255) NOT NULL,
      role ENUM('user', 'admin') DEFAULT 'user',
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )
  `;

  try {
    await pool.query(createTableSQL);
    console.log('Users table created or already exists');
  } catch (error) {
    console.error('Error creating users table:', error);
    throw error;
  }
};

// 密码加密
export const hashPassword = async (password: string): Promise<string> => {
  const salt = await bcrypt.genSalt(10);
  return bcrypt.hash(password, salt);
};

// 密码比较
export const comparePassword = async (password: string, hashedPassword: string): Promise<boolean> => {
  return bcrypt.compare(password, hashedPassword);
};

// 用户相关操作
export const User = {
  // 创建用户
  async create(username: string, password: string, role: 'user' | 'admin' = 'user'): Promise<IUser> {
    const hashedPassword = await hashPassword(password);
    const [result] = await pool.query<IUser[]>(
      'INSERT INTO users (username, password, role) VALUES (?, ?, ?)',
      [username, hashedPassword, role]
    );
    return result[0];
  },

  // 根据用户名查找用户
  async findByUsername(username: string): Promise<IUser | null> {
    const [rows] = await pool.query<IUser[]>(
      'SELECT * FROM users WHERE username = ?',
      [username]
    );
    return rows[0] || null;
  },

  // 根据ID查找用户
  async findById(id: number): Promise<IUser | null> {
    const [rows] = await pool.query<IUser[]>(
      'SELECT * FROM users WHERE id = ?',
      [id]
    );
    return rows[0] || null;
  },

  // 更新用户
  async update(id: number, data: Partial<IUser>): Promise<boolean> {
    const [result] = await pool.query(
      'UPDATE users SET ? WHERE id = ?',
      [data, id]
    );
    return (result as any).affectedRows > 0;
  },

  // 删除用户
  async delete(id: number): Promise<boolean> {
    const [result] = await pool.query(
      'DELETE FROM users WHERE id = ?',
      [id]
    );
    return (result as any).affectedRows > 0;
  }
}; 